package com.itheima.controller;

import com.itheima.bean.Employee;
import com.itheima.bean.PageBean;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.exception.CustomException;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;

/**
 * @author tang
 * @date 2022/11/21 16:43
 */
@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        String username = employee.getUsername();
        String password = employee.getPassword();
        log.info("当前用户的id{}", BaseContext.getCurrentId());
        return employeeService.login(username, password, session);
    }

    /**
     * 用户退出
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        session.invalidate();
        log.info("当前用户的id{}", BaseContext.getCurrentId());
        return R.success("删除成功");
    }

    /**
     * 添加员工
     */
    @PostMapping
    public R<String> add(@RequestBody Employee employee) {
        log.info("当前用户的id{}", BaseContext.getCurrentId());
        return employeeService.add(employee);
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<PageBean<Employee>> findPage(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(required = false) String name) {
        return employeeService.findPage(page, pageSize, name);
    }

    /**
     * 修改回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> queryEmployeeById(@PathVariable Long id) {
        if (id == null) {
            throw new CustomException("数据异常");
        }
        return employeeService.queryEmployeeById(id);
    }

    /**
     * 点击保存
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> editEmployee(@RequestBody Employee employee) {
        if (employee == null) {
            throw new CustomException("数据异常");
        }
        return employeeService.editEmployee(employee);
    }
}
